package org.stock.agent.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import org.stock.agent.model.ComprehensiveAnalysis;
import org.stock.agent.service.ChiefAnalyst;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RestController
@RequestMapping("/api/analysis")
public class StockAnalysisController {

    @Autowired
    private ChiefAnalyst chiefAnalyst;

    private final ExecutorService executor = Executors.newCachedThreadPool();

    @GetMapping("/stock")
    public ComprehensiveAnalysis analyzeStock(@RequestParam("symbol") String symbol) {
        ComprehensiveAnalysis comprehensiveAnalysis = chiefAnalyst.analyzeStock(symbol);
        System.out.println(comprehensiveAnalysis.toString());
        return comprehensiveAnalysis;
    }

    @PostMapping("/stock")
    public ComprehensiveAnalysis analyzeStockPost(@RequestBody StockAnalysisRequest request) {
        return chiefAnalyst.analyzeStock(request.getSymbol());
    }

    @GetMapping(value = "/stock/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter analyzeStockStream(@RequestParam String symbol) {
        SseEmitter emitter = new SseEmitter(Long.MAX_VALUE);
        
        executor.submit(() -> {
            try {
                // 发送开始分析消息
                emitter.send(SseEmitter.event()
                        .name("message")
                        .data("{\"type\":\"thinking\",\"content\":\"开始分析股票 " + symbol + "...\"}"));
                
                // 模拟分析过程 - 实际调用分析服务
                emitter.send(SseEmitter.event()
                        .name("message")
                        .data("{\"type\":\"thinking\",\"content\":\"\\n正在获取技术分析数据...\"}"));
                
                Thread.sleep(800);
                emitter.send(SseEmitter.event()
                        .name("message")
                        .data("{\"type\":\"thinking\",\"content\":\"\\n正在获取基本面数据...\"}"));
                
                Thread.sleep(800);
                emitter.send(SseEmitter.event()
                        .name("message")
                        .data("{\"type\":\"thinking\",\"content\":\"\\n正在获取市场情绪数据...\"}"));
                
                Thread.sleep(800);
                emitter.send(SseEmitter.event()
                        .name("message")
                        .data("{\"type\":\"thinking\",\"content\":\"\\n正在进行综合分析...\"}"));
                
                // 调用真正的分析服务
                ComprehensiveAnalysis analysis = chiefAnalyst.analyzeStock(symbol);
                
                // 发送分析过程中的思考信息
                emitter.send(SseEmitter.event()
                        .name("message")
                        .data("{\"type\":\"thinking\",\"content\":\"\\n分析完成，正在生成报告...\"}"));
                
                Thread.sleep(500);
                
                // 构建结果展示
                StringBuilder resultBuilder = new StringBuilder();
                resultBuilder.append("分析完成！\\n\\n");
                resultBuilder.append("股票代码: ").append(analysis.getSymbol()).append("\\n");
                resultBuilder.append("投资建议: ").append(analysis.getInvestmentRecommendation()).append("\\n");
                //resultBuilder.append("总体概率: ").append(String.format("%.2f%%", analysis.getOverallProbability() * 100)).append("\\n\\n");
                
                resultBuilder.append("详细分析:\\n");
                resultBuilder.append("详细理由: ").append(analysis.getDetailedReasoning()).append("\\n");
                resultBuilder.append("关键支撑因素: ").append(analysis.getKeySupportingFactors()).append("\\n");
                resultBuilder.append("主要风险: ").append(analysis.getMainRisks()).append("\\n\\n");
                
                /*resultBuilder.append("各角色分析概率:\\n");
                if (analysis.getRoleProbabilities() != null) {
                    for (Map.Entry<String, String> entry : analysis.getRoleProbabilities().entrySet()) {
                        resultBuilder.append("  ").append(entry.getKey()).append(": ")
                                .append(String.format("%.2f%%", entry.getValue() * 100)).append("\\n");
                    }
                }*/
                
                resultBuilder.append("\\n关注事件: ").append(analysis.getKeyEventsToWatch()).append("\\n");
                
                emitter.send(SseEmitter.event()
                        .name("message")
                        .data("{\"type\":\"result\",\"content\":\"" + resultBuilder.toString() + "\"}"));
                
                emitter.send(SseEmitter.event().name("end").data(""));
                emitter.complete();
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    emitter.send(SseEmitter.event()
                            .name("error")
                            .data("{\"error\":\"分析过程中发生错误: " + e.getMessage() + "\"}"));
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                } finally {
                    emitter.complete();
                }
            }
        });
        
        return emitter;
    }

    public static class StockAnalysisRequest {
        private String symbol;

        public String getSymbol() {
            return symbol;
        }

        public void setSymbol(String symbol) {
            this.symbol = symbol;
        }
    }
}